
const Msgs = require('./Msgs')
const userHelp=require('../users/userHelp')
const GroupHelp=require('../../database/groups/GroupHelp')
const UnReadMsgHelp=require('../../database/unread/UnReadMsgHelp')
const CountsHelp=require('../../database/count/CountsHelp')


//保存消息
exports.saveMsg=async (obj) => {

    let res=await findMsgByClientTime(obj.client_time)
    if(res){
        return true
    }

    let time=new Date().getTime()

    let mid=time+''+parseInt(Math.random()*1000)-0
    let from_uid=obj.from_uid-0
    let whoRead={[from_uid]:true}
    let newObj=Object.assign(obj,{time:time,mid:mid,whoRead:JSON.stringify(whoRead)})

    let msg=new Msgs(newObj)

    await msg.save();

    CountsHelp.updateCounts(obj.from_uid-0)  //记录聊天数目

    return false
}



const findMsgByClientTime=async (client_time) => {
    let msg=await Msgs.findOne({
        client_time:client_time
    })
    return msg
}
exports.findMsgByClientTime=findMsgByClientTime





//获取单聊消息
const getMsgList=async (to_uid,from_uid,start,limit) => {

    let  msgs=await Msgs.find(
        {
            $or: [ //多条件，数组
                {from_uid: from_uid, to_uid: to_uid,},
                {from_uid: to_uid, to_uid: from_uid},
            ]
        }
    )

    if(start&&limit){
        let begin_=(start-1)*limit
        let end_=start*limit
        return msgs.slice(begin_,end_)
    }
    else{
        return msgs
    }
}
exports.getMsgList=getMsgList




//倒序
exports.getMsgListReverse=async (to_uid,from_uid,start,limit) => {

    let  msgs=await Msgs.find(
        {
            $or: [ //多条件，数组
                {from_uid: from_uid, to_uid: to_uid},
                {from_uid: to_uid, to_uid: from_uid}
            ]
        }
    )

    msgs=msgs.reverse()

    if(start&&limit){
        let begin_=(start-1)*limit
        let end_=start*limit
        return msgs.slice(begin_,end_)
    }
    else{
        return msgs
    }
}



//获取群聊消息
const getGroupMsgList=async (gid,from_uid,start,limit) => {

    let  msgs=await Msgs.find(
        {
          gid:gid
        }
    ).sort('mid')


    if(start&&limit){
        let begin_=(start-1)*limit
        let end_=start*limit
        return msgs.slice(begin_,end_)
    }
    else{
        return msgs
    }
}
exports.getGroupMsgList=getGroupMsgList





//只推送最后一条消息
exports.pushLastMsg=async(to_uid,from_uid,lastmsg)=>{

    let user=await userHelp.getUserInfo(from_uid)
    if(user.code==1){
        return null
    }
    else{
        let unRead=await UnReadMsgHelp.getUnReadMsgNum(to_uid,from_uid)

        let latmsh_copy=JSON.parse(JSON.stringify(lastmsg))
        let new_msg=makeMsg(latmsh_copy,user,unRead,to_uid)

        return  new_msg
    }
}




//只推送最后一条消息（推给自己）
exports.pushLastMsgForMe=async(to_uid,myuid,lastmsg)=>{

    let user=await userHelp.getUserInfo(to_uid)

    let unRead=await UnReadMsgHelp.getUnReadMsgNum(myuid,to_uid)


    if(user.code==1){
        return null
    }
    else{

        let latmsh_copy=JSON.parse(JSON.stringify(lastmsg))
        let new_msg=makeMsg(latmsh_copy,user,unRead,myuid)

        return  new_msg
    }
}



//
exports.pushLastMsgForGroup=async(to_uid,gid,lastmsg)=>{

    let user=await GroupHelp.getGroupInfo(gid)

    let unRead=await UnReadMsgHelp.getUnReadMsgNum(to_uid,gid)

    let latmsg_copy=JSON.parse(JSON.stringify(lastmsg))
    let new_msg=makeMsg(latmsg_copy,user,unRead,to_uid)

    return  new_msg

}





//将单聊群聊，转成相同的格式
function makeMsg(lastmsgs_,user,unRead,to_uid) {

    if(user.gid){
        let obj={
            id:user.gid+""+to_uid,        //原来的id+自己的id,并转成字符串
            gid:user.gid,
            uid:0,
            gname:user.gname,
            username:"",
            name:"",
            pic:"",
            userlist:user.userlist,
            owner_uid:user.owner_uid,
            unRead:unRead,
            to_uid:0,
        }
        return Object.assign(lastmsgs_,obj)
    }
    else{
        let pic=user.pic||""
        let obj={
            id:user.uid+""+to_uid,
            uid:user.uid,
            gid:0,
            gname:"",
            username:user.username||"",
            name:user.name||"",
            pic:pic,
            userlist:"",
            owner_uid:0,
            unRead:unRead
        }

        return Object.assign(lastmsgs_,obj)
    }
}





//读取消息
exports.readMsg=async(uid,myuid)=>{

    if(!uid){
        return ''
    }
    if(!myuid){
        return ''
    }

    let res=await UnReadMsgHelp.getUnReadMsg(myuid)

    if(res){
        let msg_ids=res.msg_ids

        let len=0
        if(msg_ids[uid]){
            len=msg_ids[uid].length
        }


        msg_ids[uid]=[]

        let unRead=res.unRead-len

        let new_obj=Object.assign(res,{msg_ids:msg_ids,unRead:unRead})


        UnReadMsgHelp.updateUnReadMsg(new_obj,myuid)
    }


    return ''

}




//读取群消息
exports.readGroupMsg=async(gid,myuid)=>{

    if(!myuid){
        return ''
    }

    let res=await UnReadMsgHelp.getUnReadMsg(myuid)

    if(res){
        let msg_ids=res.msg_ids

        if(msg_ids[gid]){
            let len=msg_ids[gid].length

            msg_ids[gid]=[]

            let unRead=res.unRead-len

            let new_obj=Object.assign(res,{msg_ids:msg_ids,unRead:unRead})

            UnReadMsgHelp.updateUnReadMsg(new_obj,myuid)
        }

    }


    return ''
}




//查询消息
exports.findMsg=async(mid)=>{

    let msgs=await Msgs.findOne({mid:mid})

    return msgs

}



//删除消息
exports.removeMsg=async(mid)=>{

    await Msgs.remove({mid:mid})

    return ''

}






//以下接口只用来调试，不供前端使用
//群消息总数
exports.getGroupMsgListLength=async (gid) => {
    let  count=await Msgs.find(
        {
            gid:gid
        }
    ).count()

    return count
}



exports.findAllMsg=async () => {
    let msgs=await Msgs.find()
    let len=msgs.length
    return len
}



